﻿<template>
  <div>
    <el-upload ref = 'upload'
      :action = 'actionUrl' :auto-upload = "true" :http-request = "submitUpload" accept = 'image/*' :file-list = 'fileList'
      list-type = "picture-card" :on-exceed = 'onExceed' :class = "widget.options.disabled ? 'hiddenUploadInput' : ''"
      :on-preview = "handlePictureCardPreview" :limit = 'limit' :disabled = 'showProgress'
      :before-remove = 'removeUpload'>
      <i class = "el-icon-plus" v-if = "!showProgress"></i>
      <el-progress v-if = "showProgress" type = "circle" :percentage = "currentPercentage"
      :width = '120' style = 'margin-top:10px' :format = 'progressFormat'></el-progress>
    </el-upload>
    <el-dialog :visible.sync = "dialogVisible" append-to-body title = '图片预览' width = '50%'>
      <el-image style = 'width:100%;height:100%'  class = "show_uploadPic"
      :src = "dialogImageUrl" title = '点击查看原图' :preview-src-list = 'previewSrcList'></el-image>
    </el-dialog>
    <span v-if = "widget.type === 'Picture' && widget.options.disabled && !dataModel">暂无图片</span>
    <span v-if = "widget.type !== 'Picture' && widget.options.disabled && (dataModel && !dataModel.length)">暂无图片</span>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  props: ['dataModel', 'widget', 'changeModels', 'showEditElementDataDialog'],
  data () {
    return {
      actionUrl: `${$URL.IMG_UPLOAD_URL}`,
      fileList: [],
      fileReader: '',
      myDataModel: this.dataModel || null,
      limit: null,
      dialogImageUrl: '',
      dialogVisible: false,
      // 上传到数据库的中图片
      hadUploadPicArray: [],
      // 图片预览
      previewSrcList: [],
      // 上传进度展示
      showProgress: false,
      currentPercentage: 0
    }
  },
  mounted () {
    if (!window.FileReader) {
      this.$message({
        message: '您的浏览器不支持 FileReader API',
        type: 'warning'
      })
    } else {
      this.fileReader = new FileReader()
    }
    this.initPage()
  },
  methods: {
    // 初始化页面时
    initPage () {
      if (this.widget.type === 'Picture') {
        this.limit = 1
      } else if (this.widget.type === 'Pictures') {
        this.limit = null
      } else {
        this.limit = this.widget.options.limit
      }
      this.fileList = []
      this.hadUploadPicArray = []
      // 当个图片上传时，为字符串类型
      if (this.widget.type === 'Picture') {
        this.myDataModel = this.dataModel ? this.dataModel : ''
        if (this.dataModel) {
          let currentPic = this.dataModel
          let obj = {
            linkUrl: currentPic,
            url: currentPic.indexOf('/dl/') !== -1 ? currentPic.replace('/dl/', '/') : currentPic
          }
          this.fileList.push(obj)
          this.hadUploadPicArray.push(obj)
        }
      } else if (this.widget.type === 'Pictures') {
        this.myDataModel = (this.dataModel && this.dataModel.length) ? this.dataModel : []
        if (this.dataModel && this.dataModel.length) {
          this.dataModel.forEach((item, index) => {
            let obj = {
              linkUrl: item,
              url: item.indexOf('/dl/') !== -1 ? item.replace('/dl/', '/') : item
            }
            this.fileList.push(obj)
            this.hadUploadPicArray.push(obj)
          })
        }
      }
    },
    // 点击预览的方法
    handlePictureCardPreview (file) {
      this.previewSrcList = []
      this.dialogImageUrl = file.url
      this.previewSrcList.push(file.url)
      this.dialogVisible = true
    },
    // 图片超过最大上传个数时
    onExceed () {
      this.$message({
        message: '最多只能上传' + this.limit + '个图片',
        type: 'warning'
      })
    },
    // 上传图片移除
    removeUpload (file) {
      if (!this.widget.options.disabled) {
        this.$confirm('确定要移除该图片么,请谨慎操作！', '提示', {
          showClose: false,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonClass: 'el-button--info',
          cancelButtonText: '取消'
        }).then(() => {
          this.$store.dispatch('changeLoadingText', '图片删除中...')
          this.$store.dispatch('changRouteLoading', true)
          // 删除文件的方法
          let downUrl = file.linkUrl
          if (downUrl) {
            if (downUrl.indexOf('/fileset/dl/') !== -1) {
              downUrl = downUrl.replace('/fileset/dl/', '/fileset/recycle/')
            } else {
              downUrl = downUrl.replace('/fileset/', '/fileset/recycle/')
            }
          }
          axios({
            url: downUrl,
            method: 'patch'
          }).then(data => {
            if (data.data.result.code === 'success') {
              // 当个图片时
              if (this.widget.type === 'Picture') {
                this.myDataModel = ''
              } else {
                // 多个图片时
                if (this.myDataModel && this.myDataModel.length) {
                  this.myDataModel.forEach((item, index) => {
                    if (item === file.linkUrl) {
                      this.myDataModel.splice(index, 1)
                    }
                  })
                }
              }
              // 移除展示的图片
              if (this.fileList.length) {
                this.fileList.forEach((item, index) => {
                  if (item.url === file.url) {
                    this.fileList.splice(index, 1)
                  }
                })
              }
              // 备用存储的图片
              if (this.hadUploadPicArray.length) {
                this.hadUploadPicArray.forEach((item, index) => {
                  if (item.url === file.url) {
                    this.hadUploadPicArray.splice(index, 1)
                  }
                })
              }
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: data.data.result.msg,
                type: 'error',
                duration: 5000
              })
            }
            this.$store.dispatch('changeLoadingText', '数据加载中...')
            this.$store.dispatch('changRouteLoading', false)
          }).catch(error => {
            this.$store.dispatch('changeLoadingText', '数据加载中...')
            this.$store.dispatch('changRouteLoading', false)
            console.log(error)
          })
        }).catch(() => {
        })
        return false
      } else {
        return false
      }
    },
    submitUpload (options) {
      let file = options.file
      if (file) {
        // 进度条相关的控件
        this.showProgress = true
        this.currentPercentage = 0
        this.fileReader.readAsDataURL(file)
        let formData = new FormData()
        formData.append('file', file)
        axios({
          url: $URL.IMG_UPLOAD_URL + '/fileset/upload_stream',
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
          },
          data: formData,
          onUploadProgress: ProgressEvent => {
            if (ProgressEvent.lengthComputable) {
              let currentPer = parseInt(ProgressEvent.loaded / ProgressEvent.total * 10000) / 100
              this.currentPercentage = currentPer > 100 ? 100 : currentPer
            }
          }
        }).then(data => {
          let dataResult = data.data.result
          if (dataResult.code === 'success') {
            this.currentPercentage = 100
            this.$message({
              message: '上传成功',
              type: 'success'
            })
            this.showProgress = false
            let obj = {
              linkUrl: dataResult.link_url,
              url: (dataResult.link_url && dataResult.link_url.indexOf('/dl/') !== -1) ? dataResult.link_url.replace('/dl/', '/') : dataResult.link_url
            }
            this.fileList.push(obj)
            // 同时存储在hadUploadPicArray中，以方便在上传失败时，将现有的图片信息展示出来
            this.hadUploadPicArray.push(obj)
            // 单个图片为字符串，多个图片为数组
            if (this.widget.type === 'Picture') {
              this.myDataModel = dataResult.link_url
            } else {
              this.myDataModel.push(dataResult.link_url)
            }
          } else {
            // 上传失败的提示
            this.uploadFailedMsg()
          }
        }).catch(error => {
          // 上传失败的提示
          this.uploadFailedMsg()
          console.log(error)
        })
      }
    },
    // 进度条的文字格式化
    progressFormat (percentage) {
      return percentage === 100 ? '处理中...' : `${percentage}%`
    },
    // 上传失败的提示
    uploadFailedMsg () {
      // 先清空上传列表中的内容
      this.fileList = []
      this.$refs.upload.clearFiles()
      // 将以成功上传的图片展示在上传列表中--不是单个图片时
      if (this.widget.type !== 'Picture') {
        if (this.hadUploadPicArray && this.hadUploadPicArray.length) {
          this.hadUploadPicArray.forEach(item => {
            if (item) {
              let obj = {
                linkUrl: item.link_url,
                url: item.url
              }
              this.fileList.push(obj)
            }
          })
        }
      }
      this.$message({
        message: '上传失败',
        type: 'error',
        duration: 3000
      })
      this.showProgress = false
    },
    // 根据url获取到图片的基本信息
    getFileBasicInfo (fileUrl, currentIndex) {
      if (fileUrl) {
        axios({
          url: fileUrl,
          method: 'get'
        }).then(data => {
          let dataInfo = data.data.result
          if (dataInfo.code === 'success') {
            let obj = {
              linkUrl: fileUrl,
              url: 'data:image/png;base64,' + dataInfo.file
            }
            if (this.widget.type === 'Picture') {
              this.fileList.push(obj)
              this.hadUploadPicArray.push(obj)
              this.$store.dispatch('changeLoadingText', '数据加载中...')
              this.$store.dispatch('changRouteLoading', false)
            } else {
              // this.$set(this.fileList, currentIndex, obj)
              // this.$set(this.hadUploadPicArray, currentIndex, obj)
              this.fileList.push(obj)
              if (currentIndex === this.dataModel.length - 1) {
                this.$store.dispatch('changeLoadingText', '数据加载中...')
                this.$store.dispatch('changRouteLoading', false)
                this.hadUploadPicArray = JSON.parse(JSON.stringify(this.fileList))
              }
            }
          } else if (dataInfo.code === 'failed') {
            this.$message({
              message: dataInfo.msg,
              type: 'error'
            })
            this.$store.dispatch('changeLoadingText', '数据加载中...')
            this.$store.dispatch('changRouteLoading', false)
          }
        }).catch(error => {
          this.$store.dispatch('changeLoadingText', '数据加载中...')
          this.$store.dispatch('changRouteLoading', false)
          console.log(error)
        })
      } else {
        this.$message({
          message: '没有获取到本图片的下载地址',
          type: 'warning'
        })
      }
    }
  },
  watch: {
    myDataModel: {
      deep: true,
      handler (val) {
        this.$emit('update:dataModel', val)
      }
    },
    showEditElementDataDialog: {
      deep: true,
      handler (val) {
        if (val) {
          this.initPage()
        }
      }
    }
  }
}
</script>
